import Router from "vue-router";
import API from "@/api/apiServer";
import store from "@/store/index";

const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
};

const constantRoutes = [
  {
    path: "/login",
    name: "Login",
    component: () => import("@/pages/Login"),
    meta: {
      title: "登录"
    }
  },
  {
    path: "/index",
    name: "Index",
    alias: "/",
    component: () => import("@/pages/Index")
  },
  {
    path: "/workshop",
    name: "workshop",
    component: () => import("@/pages/WorkShop")
  },
  {
    path:"/equipmentWorkShop",
    name:'equipmentWorkShop',
    component:() => import("@/pages/equipmentWorkShop")
  }
];

const router = new Router({
  mode: "hash",
  // scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
});

// 设置路由白名单
const whiteList = ["/login"];

router.beforeEach(async (to, from, next) => {
  let userInfo = JSON.parse(localStorage.getItem("userInfo"));
  if (to.meta.title) {
    // document.title = to.meta.title;
  }
  // 判断本地缓存是否有用户信息
  if (userInfo && Object.keys(userInfo).length > 0) {
    // 获取user信息
    const res1 = await API.UserFindById({ id: userInfo.id });
    if (res1.code !== 200) {
      let userName = localStorage.getItem("userName");
      let password = localStorage.getItem("password");
      let state = localStorage.getItem("state");
      localStorage.clear();
      if (userName && password && state) {
        localStorage.setItem("userName", userName);
        localStorage.setItem("password", password);
        localStorage.setItem("state", state);
      }
      next({ name: "Login" });
      return;
    }

    store.commit("mes/SetMesUserInfo", res1.data);
    // // 重新存储用户信息
    localStorage.setItem("userInfo", JSON.stringify(res1.data));

    let userId = userInfo.id;
    // 通过接口获取最新路由表
    const res = await API.UserResources({ id: userId });

    if (res.code !== 200) {
      this.$message.error("获取菜单列表失败");
      return;
    }
    localStorage.setItem("menuArr", JSON.stringify(res.data.treeList));
    let newRoutes = res.data.treeList;
    // // 遍历权限中的授权页面
    if (newRoutes) {
      store.commit("menu/saveMenuLists", newRoutes);
    }

    store.commit("menu/setActiveMenuPath", { path: to.path });

    // 判断router中有没有被授权的路由
    let hasRoutes = router.getRoutes();
    if (
      store.state.menu.allAuthRoutes.findIndex(item => item.path == to.path) ==
      -1
    ) {
      // 如果目标页面不在授权路由表中,则前往login页面
      if (to.path === "/login") {
        next();
      } else {
        next({ name: "Login" });
      }
    } else {
      if (hasRoutes.findIndex(item => item.path == to.path) == -1) {
        // 如果目标路由不在hasRoutes中,则重新加载路由表
        let authorizationRoutes = [];
        constantRoutes.forEach(item => {
          if (item.name == "Index") {
            item.children = [...store.state.menu.allAuthRoutes];
          }
          authorizationRoutes.push(item);
        });
        router.addRoutes(authorizationRoutes);

        next({ ...to, replace: true });
      } else {
        // 如果是去登录界面
        if (to.path === "/login" || to.path === "/index" || to.path === "/") {
          // 直接跳转到菜单的第一项
          let path = store.state.menu.firstMenuPath;
          next({ path });
        } else {
          // 如果不是,前往目标页面,
          store.commit("menu/getAuthBtnlists", { path: to.path });
          next();
        }
      }
    }
  } else {
    // 如果在免登录白名单中，直接进入,否则一律跳转到'login'界面
    if (whiteList.indexOf(to.path) != -1) {
      next();
    } else {
      next({ name: "Login" });
    }
  }
});

export default router;
